<template>
  <Tab @goBack="goBack" :tabs="tabs" :current="current">
    <div slot="index">
      <el-form :inline="true" label-width="80px">
        <el-form-item label="手机号码">
          <el-input
            v-model="queryParams.mobile"
            placeholder="手机号码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="昵称/姓名">
          <el-input
            v-model="queryParams.nickname"
            placeholder="昵称/姓名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="来源">
          <el-select @keyup.enter.native="handleQuery" v-model="queryParams.source" placeholder="来源" clearable
                     size="small">
            <el-option
              v-for="dict in sourceOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select @keyup.enter.native="handleQuery" v-model="queryParams.role" placeholder="角色" clearable
                     size="small">
            <el-option
              v-for="dict in roleOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select @keyup.enter.native="handleQuery" v-model="queryParams.status" placeholder="状态" clearable
                     size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="省/市">
          <el-select :filterable="true" style="width: 100px" @keyup.enter.native="handleQuery"
                     v-model="queryParams.provinceId" placeholder="省" clearable size="small" @clear="provinceClear"
                     @change="provinceChange">
            <el-option
              v-for="dict in areaList"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          -
          <el-select filterable style="width: 100px" @keyup.enter.native="handleQuery" v-model="queryParams.cityId"
                     placeholder="市" clearable size="small">
            <el-option
              v-for="dict in cityList"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="startTime"
            size="small"
            style="width: 220px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="primary" icon="el-icon-plus" v-hasPermi="['maker:list:add']" size="mini"
                     @click="handleInsert">新增
          </el-button>
        </el-form-item>


      </el-form>

      <el-table v-loading="loading" :data="postList">
        <!-- <el-table-column type="expand">
           <template slot-scope="scope">
             <el-form label-position="left" inline class="yy-table-expand">
               <el-form-item label="头像" style="display: block">
                 <el-popover placement="right" title="" trigger="click">
                   <img :src="scope.row.avatar" alt="">
                   <img slot="reference" :src="scope.row.avatar" alt="" style="max-height: 50px;max-width: 50px">
                 </el-popover>
               </el-form-item>
               <el-form-item label="创建时间">
                 <span>{{ scope.row.createtime }}</span>
               </el-form-item>
             </el-form>
           </template>
         </el-table-column>-->
        <el-table-column label="用户编号" align="center" prop="idNo" :show-tooltip-when-overflow="true">
          <template slot-scope="scope">
            <router-link @click.native="handleJump(scope.row,'invite')" class="link-type" title="下级记录" to="">
              <span>{{scope.row.idNo}}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="昵称" align="center" :show-tooltip-when-overflow="true">
          <template slot-scope="scope">
            <el-link title="查看详情" type="primary"
                     @click="handleUserInfo(scope.row)">{{scope.row.nickname}}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" align="center">
          <template slot-scope="scope">
            <el-popover placement="top-start" title="手机号码" width="250" trigger="hover">
              <div>{{scope.row.mobile}}</div>
              <span slot="reference" v-if="scope.row.mobile">{{ scope.row.mobile.substr(0,6)+'...' }}</span>
              <span slot="reference" v-else class="text-info">无</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="真实姓名" align="center">
          <template slot-scope="scope">
            <span :class="scope.row.realName?'':'text-warning'">{{ scope.row.realName?scope.row.realName:'未实名' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" align="center" prop="role" :formatter="roleFormat"/>
        <el-table-column label="省市" align="center" :formatter="provinceAndCityFormat"
                         :show-tooltip-when-overflow="true"/>
        <el-table-column label="线上推荐人" align="center" :show-tooltip-when-overflow="true">
          <template slot-scope="scope">
            <el-link v-if="scope.row.reference" title="查看详情" type="primary"
                     @click="handleUserInfo({role:scope.row.referenceRole,userId:scope.row.referenceId})">
              {{scope.row.reference}}
            </el-link>
            <span v-else class="text-warning">无</span>
          </template>
        </el-table-column>
        <el-table-column label="线下推荐人" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-link v-if="scope.row.inviteUserId" title="查看详情" type="primary"
                     @click="handleUserInfo({userId:scope.row.inviteUserId,role:scope.row.inviteRole})">
              {{scope.row.inviteUsername}}
            </el-link>
            <span v-else class="text-warning">无</span>
          </template>
        </el-table-column>
        <el-table-column label="创客来源" align="center" prop="source" :formatter="sourceFormat"/>


        <el-table-column label="购买数量" align="center">
          <template slot-scope="scope">
            <router-link @click.native="handleJump(scope.row,'buy')" to=""
                         class="link-type" title="购买记录">
              <span>{{((scope.row.amount+scope.row.account)/150).toFixed(0)}}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="总基金" align="center">
          <template slot-scope="scope">
            <router-link to="" @click.native="handleJump(scope.row,'asset')"
                         class="link-type" title="资产记录">
              <span>{{formatCurrency(scope.row.amount+scope.row.account) }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="剩余基金" align="center">
          <template slot-scope="scope">
            <span>{{formatCurrency(scope.row.account) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="已发放基金" align="center">
          <template slot-scope="scope">
            <router-link @click.native="handleJump(scope.row,'data')" to="" class="link-type" title="发放记录">
              <span>{{formatCurrency(scope.row.amount) }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="发放数量" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.num||0}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" :show-tooltip-when-overflow="true"
                         prop="createtime"></el-table-column>

        <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['maker:list:update']"
            >充值
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleJump(scope.row,'team')"
            >团队
            </el-button>
            <!-- <el-button
              size="mini"
              type="text"
              @click="handleInvite(scope.row)"
            >创客下级
              v-hasPermi="['maker:sendlog:list']"
            </el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <UserInfo :show="userInfoShow" @close="handleUserInfoClose" v-if="userItem" :item="userItem"></UserInfo>

      <el-dialog :title="title" :visible.sync="userInfoOpen" width="600px">
        <el-form ref="form" label-width="150px">
          <el-form-item label="用户编号:">
            {{user.idNo}}
          </el-form-item>
          <el-form-item label="昵称:">
            {{user.nickname}}
          </el-form-item>
          <el-form-item label="真实姓名:">
            <span :class="user.realName?'':'text-warning'">{{ user.realName?user.realName:'未实名' }}</span>
          </el-form-item>
          <el-form-item label="手机号码:">
            {{user.mobile}}
          </el-form-item>
          <el-form-item label="角色:">
            {{roleFormat(user)}}
          </el-form-item>
          <el-form-item label="性别:">
            {{genderFormat(user)}}
          </el-form-item>
          <el-form-item label="创建时间:">
            {{ dateFormat(user.createtime) }}
          </el-form-item>
        </el-form>
      </el-dialog>


      <el-dialog :title="title" :visible.sync="open" width="600px" :close-on-click-modal="false">
        <el-form ref="form" :model="form" :rules="addRules" label-width="150px">
          <el-form-item label="用户" prop="userId" v-if="!this.form.makerId">
            <el-select v-model="form.userId"
                       style="width: 300px;"
                       @change="userChange"
                       filterable
                       remote
                       reserve-keyword
                       placeholder="请输入手机号码/昵称/姓名查询"
                       :remote-method="remoteFindUserList"
                       :loading="selectLoading">
              <el-option
                v-for="item in addOptions"
                :key="item.id"
                :label="item.nickname+'/'+item.mobile+'/'+roleFormat(item)"
                :value="item.id">
                <span style="float: left">{{ item.mobile }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ roleFormat(item) }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="单价(元)" prop="singleamount">
            <el-input-number v-model="form.singleamount" :precision="2" :step="150" :disabled="true"></el-input-number>
          </el-form-item>

          <el-form-item label="数量(张)" prop="number">
            <el-input-number v-model="form.number" :step="1" :max="999" :min="1"></el-input-number>
          </el-form-item>

          <el-form-item label="总价(元)">
            <span class="text-info">{{totalAmount}}</span>
          </el-form-item>


          <el-form-item label="推荐人(线下)" prop="inviteUserId" v-if="!this.form.makerId">
            <el-select v-if="!form.inviteUsername"
                       v-model="form.inviteUserId"
                       style="width: 300px;"
                       filterable
                       remote
                       reserve-keyword
                       placeholder="请输入手机号码/昵称/姓名查询"
                       :remote-method="remoteMethod"
                       :loading="selectLoading">
              <el-option
                v-for="item in options"
                :key="item.idNo"
                :label="item.nickname+'/'+item.mobile+'/'+roleFormat(item)"
                :value="item.userId">
                <span style="float: left">{{ item.mobile }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ roleFormat(item) }}</span>
              </el-option>
            </el-select>
            <!--<span>{{ form.inviteUsername }}</span>-->
            <!--<span  class="text-navy" style="display: block"></span>-->
          </el-form-item>

          <el-form-item label="推荐人(线上)" v-if="!this.form.makerId">
            <span v-if="itemUser">{{itemUser.inviteNickname+'-'+itemUser.inviteMobile+'-'+roleFormat({role:itemUser.inviteRole})}}</span>
            <span v-else class="text-warning">暂无</span>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="addLoading" @click.native.prevent="submitForm">
            <span v-if="!addLoading">提 交</span>
            <span v-else>提 交 中...</span>
          </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
    <div slot="data">
      <Data :row="row" @goBack="goBack"></Data>
    </div>

    <div slot="buy">
      <Buy :row="row" @goBack="goBack"></Buy>
    </div>

    <div slot="invite">
      <Invite :row="row" @goBack="goBack"></Invite>
    </div>

    <div slot="asset">
      <Asset :row="row" @goBack="goBack"></Asset>
    </div>

    <div slot="team">
      <Team :row="row" @goBack="goBack" :roleOptions="roleOptions"></Team>
    </div>

  </Tab>
</template>

<script>
  import {list, changeStatus, updateMaker, findUserList, addMaker, offlineUserList} from "@/api/maker/list";
  import {list as userList} from "@/api/maker/user";
  import {area} from "@/utils/area";
  import Tab from "@/components/Tab";
  import Asset from './asset';
  import Buy from './buy';
  import Data from './data';
  import Invite from './invite';
  import Team from './team';
  import UserInfo from '@/views/components/user';
  import mixin from '@/views/components/user/mixin';

  export default {
    mixins: [mixin],
    components: {Tab, Asset, Buy, Data, Invite, UserInfo, Team},
    data() {
      return {
        addLoading: false,
        row: undefined,
        itemUser: undefined,
        current: 'index',
        tabs: [
          {index: 'index', name: ''},
          {'index': 'asset', name: '基金记录'},
          {'index': 'invite', name: '下级记录'},
          {'index': 'data', name: '发放记录'},
          {'index': 'buy', name: '购买记录'},
          {'index': 'team', name: '创客团队'},
        ],
        selectLoading: false,
        addOpen: false,
        startTime: '',
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 岗位表格数据
        postList: [],
        areaList: [],
        cityList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        userInfoOpen: false,
        // 状态数据字典
        statusOptions: [],
        roleOptions: [],
        sourceOptions: [],
        genderOptions: [],
        addOptions: [],
        options: [],
        user: {},
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          mobile: undefined,
          nickname: undefined,
          status: undefined,
          startTime: undefined,
          endTime: undefined,
          role: undefined,
          provinceId: undefined,
          cityId: undefined,
        },
        form: {
          markId: undefined,
          userId: undefined,
          singleamount: 150,
          number: 1,
          mobile: undefined,
          role: undefined,
          inviteUserId: undefined
        },
        rules: {
          singleamount: [
            {required: true}
          ],
          number: [
            {required: true}
          ]
        },
        addRules: {
          userId: [{required: true, message: '请选择用户', trigger: 'blur'}],
          inviteUserId: [{required: true, message: '请选择线下推荐人', trigger: 'blur'}]
        }
      };
    },
    created() {
      this.getDicts("sys_user_sex").then(response => {
        this.genderOptions = response.data;
      });
      this.getDicts("maker_status").then(response => {
        this.statusOptions = response.data;
      });
      this.getDicts("yy_user_role").then(response => {
        this.roleOptions = response.data;
      });
      this.getDicts("yy_maker_source").then(response => {
        this.sourceOptions = response.data;
      });
      area().then(response => {
        this.areaList = response;
      });
      this.getList();
    },
    computed: {
      totalAmount: function () {
        return this.form.singleamount * this.form.number;
      }
    },
    methods: {
      userChange(value) {
        for (let i = 0; i < this.addOptions.length; i++) {
          let item = this.addOptions[i];
          if (item.id === value) {
            if (item.inviteUserId) {
              this.itemUser = item;
            }
            break;
          }
        }
      },
      provinceClear() {
        this.queryParams.cityId = '';
        this.cityList = [];
      },
      provinceChange(value) {
        if (value) {
          this.queryParams.cityId = '';
          this.cityList = this.areaList.filter(item => item.value === value)[0].children;
        }
      },
      referenceInfo(referenceId) {
        this.title = '用户详情';
        userList({userId: referenceId}).then(response => {
          this.userInfoOpen = true;
          this.user = response.rows[0];
          console.log(this.user);
        });

      },
      remoteFindUserList(query) {
        if (query && query.trim()) {
          this.selectLoading = true;
          findUserList({'mobile': query}).then(res => {
            this.addOptions = res.rows;
            this.selectLoading = false;
          });
        }
      },
      remoteMethod(query) {
        if (query && query.trim()) {
          if (!this.form.userId) {
            this.msgInfo('请先查询用户');
            return;
          }
          let item;
          for (let i = 0; i < this.addOptions.length; i++) {
            if (this.addOptions[i].id === this.form.userId) {
              item = this.addOptions[i];
              console.log(item);
              break;
            }
          }
          this.selectLoading = true;
          this.form.mobile = item.mobile;
          offlineUserList({mobile: query, selfMobile: item.mobile}).then(response => {
            this.options = response.rows;
            this.selectLoading = false;
          });
        }
      },
      getList() {
        this.loading = true;
        list(this.queryDateRange(this.queryParams, this.startTime)).then(response => {
          this.postList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      genderFormat(row, column) {
        return this.selectDictLabel(this.genderOptions, row.gender);
      },

      provinceAndCityFormat(row) {
        let area = [];
        if (row['provinceName']) {
          area.push(row['provinceName']);
        }
        if (row['cityName']) {
          area.push(row['cityName']);
        }
        return area.join('-');
      },
      // 岗位状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      roleFormat(row, column) {
        return this.selectDictLabel(this.roleOptions, row.role);
      },
      sourceFormat(row, column) {
        return this.selectDictLabel(this.sourceOptions, row.source);
      },
      handleUpdate(row) {
        console.log(row);
        this.reset();
        this.title = "拓客卡充值";
        this.form = {
          makerId: row.id,
          userId: row.userId,
          mobile: row.mobile,
          singleamount: 150,
          number: 1
        };
        this.open = true;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        if (this.startTime) {
          this.queryParams.startTime = this.startTime[0] + " 00:00:00";
          this.queryParams.endTime = this.startTime[1] + " 23:59:59";
        } else {
          this.queryParams.startTime = null;
          this.queryParams.endTime = null;
        }
        this.queryParams.pageNum = 1;
        this.getList();
      },
      handleStatusChange(row) {
        let text = row.status === 0 ? "已关闭" : "创业中";
        this.$confirm("确定要设置[" + row.nickname + "]的状态为:" + text + "?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return changeStatus({id: row.id, status: row.status});
        }).then(() => {
          this.msgSuccess("设置成功");
        }).catch(function () {
          row.status = row.status === 0 ? 1 : 0;
        });
      },
      cancel() {
        this.open = false;
        this.reset();
      },
      reset() {
        this.itemUser = undefined;
        this.options = [];
        this.addOptions = [];
        this.form = {
          id: undefined,
          userId: undefined,
          singleamount: 150,
          number: 1,
          mobile: undefined,
          role: undefined,
          reference: undefined
        };
        this.addLoading = false;
        this.resetForm("form");
      },
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.addLoading = true;
            if (this.form.makerId) {
              updateMaker(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("充值成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addMaker(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("操作成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }

          }
        });
      },
      handleJump(row, url) {
        this.row = row;
        console.dir(this.row);
        this.current = url;
      },
      handleInsert() {
        this.reset();
        this.title = '添加创客';
        this.open = true;
      },
      goBack(message) {
        this.current = 'index';
      }
    }
  };
</script>
<style type="scope">
  .el-select-dropdown__empty {
    min-width: 100px;
  }
</style>
